<template>
	<div class="container">
		<h1 style="text-align: center;font-weight: bold;">{{ id ? '修改' : '创建' }}周转料材料计划</h1>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="savePlan">
			<a-row :gutter="20">
				<a-col :span="24">
					<h3>计划信息</h3>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :disabled="route.query.parent_id > 0" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划名称" name="name" :rules="{ required: true, message: '请输入计划名称' }">
						<a-input v-model:value="formState.name" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划编号" name="code" :rules="{ required: true, message: '请输入计划编号' }">
						<a-input v-model:value="formState.code" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="附件" name="file_path">
						<a-upload v-model:file-list="formState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
							<a-button>
								<template v-if="uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传附件
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>

				<a-col v-if="route.query.parent_id > 0" :span="24">
					<h1 style="text-align: center;font-weight: bold;">物资计划清单</h1>

					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
							<a-button class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />暂存
							</a-button>
						</a-space>
					</div>
					<a-table :data-source="formState.materials" :scroll="tableScroll" :columns="planMaterialColumns" :pagination="false" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择周转料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择周转料名称" allow-clear :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'model']" :rules="{ required: true, message: '请选择型号规格' }">
									<a-select v-model:value="formState.materials[record.key].model" :show-search="true" option-filter-prop="model" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'model', label: 'modelName' }" style="width:100%" @change="(model) => changeMaterialModel(record, model)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'standard'">
								<a-form-item :name="['materials', index, 'standard']" :rules="{ required: true, message: '请输入质量标准技术要求' }">
									<a-input v-model:value="formState.materials[index]['standard']" placeholder="请输入质量标准技术要求" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" :show-search="true" placeholder="请选择" :options="unitOptions[`${record.source_id}_${record.model}`] || []" :field-names="{ value: 'unit', label: 'unit' }" style="width:100%" @change="(unit) => changeMaterialUnit(record, unit, unitOptions[`${record.source_id}_${record.model}`])"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入需用数量' }">
									<a-input-number v-model:value="formState.materials[index]['quantity']" placeholder="请输入需用数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'add_time'">
								<a-form-item :name="['materials', index, 'add_time']" :rules="{ required: true, message: '请输入计划进场时间' }">
									<a-date-picker v-model:value="formState.materials[index]['add_time']" :picker="date_type" value-format="YYYY-MM-DD" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{ required: true, message: '请输入计划租赁时长' }">
									<a-input-number v-model:value="formState.materials[index]['use_time']" placeholder="计划租赁时长" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{ required: true, message: '请选择时长计量单位' }">
									<a-select v-model:value="formState.materials[record.key].time_unit" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{ value: 'name' }" style="width:100%" disabled></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index]['memo']" placeholder="备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-button type="link" @click="copyMaterialModel(record)">
										<copy-outlined />复制
									</a-button>

									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-col>

				<!-- <a-col v-if="route.query.parent_id>0" :span="24">
					<h1 style="text-align: center;font-weight: bold;">原物资计划清单</h1>
					<a-table :data-source="oldMaterials" :scroll="tableScroll" :columns="MaterialColumns" :row-key="(record) => record.key"></a-table>
				</a-col>-->

				<a-col :span="24">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{ minRows: 4, maxRows: 6 }"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>
						<a-button v-if="!formState.parent_id || (formState.parent_id && ![0, 1, 2].includes(formState.workflow_status))" type="primary" html-type="submit">
							<save-outlined />保存
						</a-button>
						<a-workflow v-if="formState.id && formState.parent_id" v-model:status="formState.workflow_status" module="planzz" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.opr_id" @submit="submitPurchase"></a-workflow>
						<a-button @click="closeTab('/planzz')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { PlusOutlined, DeleteOutlined, DeliveredProcedureOutlined, SaveOutlined, CopyOutlined, CloseOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";
import { baseURL } from "../utils/request";

import { post, listToTree } from "../utils";

import { useRoute, useRouter } from "vue-router";
import { AWorkflow } from "@/components/index.js";
//缓存数据
const handleCache = () => {
	// console.log(formState.value);
	localStorage.setItem("planzz-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};

const router = useRouter();
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
const route = useRoute();

const id = computed(() => {
	return route.params.id || 0;
});

const formState = ref({ parent_id: route.query.parent_id || 0, materials: [] });
const projectOptions = ref([]);
const oldMaterials = ref([]);
onMounted(() => {
	const cacheData = localStorage.getItem("planzz-save");
	formState.value = JSON.parse(cacheData) || formState.value;
	const { parent_id } = formState.value;
	if (parent_id) {
		if (id.value) {
			post("plan/info", { id: id.value }).then(data => {
				//data.user_ids = data.users.map(d => d.id) || [];
				data.user_id = data.opr_user.id;
				if (data.plan_date) data.plan_date = dayjs(data.plan_date);

				data.materials = data.materials.map((d, i) => {
					d.key = i;
					const { unit, quantity, standard, add_time, use_time, useto, time_unit, memo } = d.PlanMaterial;
					d.unit = unit;
					d.quantity = quantity;
					d.standard = standard;
					d.add_time = add_time;
					d.use_time = use_time;
					d.time_unit = time_unit;
					d.useto = useto;
					d.memo = memo;
					return d;
				});

				formState.value = data;
				formState.value.file_path = JSON.parse(formState.value.file_path || '[]');
			});
		} else {
			post("plan/info", { id: parent_id }).then(data => {
				const { children, code, project_id } = data;
				formState.value = {
					...formState.value,
					name: `周转料计划${children.length + 1}`,
					code: code + `-${children.length + 1}`,
					project_id
				};
			});
		}

		// //原计划物资清单
		// post("plan/hebing", { id: parent_id }).then(data => {
		// 	oldMaterials.value = data.map((d, i) => {
		// 		d.key = i;
		// 		return d;
		// 	});
		// });
	} else if (id.value) {
		post("plan/info", { id: id.value }).then(data => {
			//data.user_ids = data.users.map(d => d.id) || [];
			// data.user_id = data.opr_user.id;
			// if (data.plan_date) data.plan_date = dayjs(data.plan_date);

			// data.materials = data.materials.map((d, i) => {
			// 	d.key = i;

			// 	const { unit, quantity, standard, add_time, use_time, useto, time_unit, memo } = d.PlanMaterial;
			// 	d.unit = unit;
			// 	d.quantity = quantity;
			// 	d.standard = standard;
			// 	d.add_time = add_time;
			// 	d.use_time = use_time;
			// 	d.time_unit = time_unit;
			// 	d.useto = useto;
			// 	d.memo = memo;
			// 	return d;
			// });

			formState.value = data;
		});
	}
	//projectOptions
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
});

const hasPoint = ref(true);
const changeProject = value => {
	const project_id = value;
	post("department/info", { id: project_id }).then(data => {
		//自动生成计划编码
		if (data.name) {
			let py_name = "";
			const name = data.company_name + "-" + data.name;
			post("util/pinyin", { value: name }).then(res => {
				res.value.forEach(d => {
					py_name += d.toUpperCase();
				});
				//获取计划最大ID
				let maxid = 0;
				post("plan/maxid", { project_id: project_id }).then(max => {
					maxid = parseInt(max) + 1;
					//formState.value.code = "ZTJGSJ-" + py_name + "-" + maxid;
					formState.value.code = "ZTJGSJ-" + py_name;
				});
			});
		}
	});
};

const { proxy } = getCurrentInstance();
const formRef = ref();
const savePlan = () => {
	//总数量检测
	let qty_error = 0;
	formState.value.materials.forEach(d => {
		if (parseFloat(d.quantity) === parseFloat(0)) {
			qty_error = 1;
		}
	});
	if (qty_error === 1) {
		proxy.$message.error("请填写计划数量");
		return;
	}

	if (hasPoint.value === false) {
		proxy.$message.error("请选择有工号的项目");
		return;
	}
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			if (route.query.parent_id > 0) {
				if (!params.materials.length) {
					proxy.$message.error("请添加材料清单");
					return;
				}
				params.materials = JSON.stringify(params.materials);
			}

			// const { plan_date, user_ids = [] } = params;
			// if (plan_date) params.plan_date = dayjs(plan_date).format("YYYY-MM-DD");
			// params.user_ids = user_ids.join(",");
			params.type = 2;
			// 一级总控新增
			if (!params.parent_id && !params.id) {
				params.workflow_status = 2;
			}
			if (params.file_path) params.file_path = JSON.stringify(params.file_path);
			post("plan/save", params)
				.then(() => {
					proxy.$message.success("信息提交成功", 1);
					if (route.query.parent_id) {
						// 提交子计划
						router.push(`/planzz/detail/${route.query.parent_id}`);
					} else {
						router.push("/planzz");
					}
					//清除缓存
					localStorage.removeItem("planzz-save");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => { });
};
const planMaterialColumns = computed(() => {
	const planMaterialColumns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			extra: 0,
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "周转料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "型号规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "质量标准技术要求",
			dataIndex: "standard",
			width: 200,
			extra: 0,
			align: "center"
		},
		{
			title: "计量单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "需用数量",
			dataIndex: "quantity",
			width: 100,
			extra: 0,
			align: "center"
		},
		{
			title: "计划进场时间",
			dataIndex: "add_time",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "计划租赁时长",
			dataIndex: "use_time",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "租赁时长单位",
			dataIndex: "time_unit",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "备注",
			dataIndex: "memo",
			width: 200,
			extra: 0,
			align: "center"
		},
		{
			title: "操作",
			key: "operation",
			sorter: false,
			fixed: "right",
			width: 160,
			align: "center"
		}
	];
	return planMaterialColumns;
});

const MaterialColumns = computed(() => {
	const MaterialColumns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			extra: 0,
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "周转料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "型号规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "质量标准技术要求",
			dataIndex: "standard",
			width: 200,
			extra: 0,
			align: "center"
		},
		{
			title: "计量单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "需用数量",
			dataIndex: "quantity",
			width: 100,
			extra: 0,
			align: "center"
		},
		{
			title: "计划进场时间",
			dataIndex: "add_time",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "计划租赁时长",
			dataIndex: "use_time",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "租赁时长单位",
			dataIndex: "time_unit",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "备注",
			dataIndex: "memo",
			width: 200,
			extra: 0,
			align: "center"
		}
	];
	return MaterialColumns;
});

const unitOptions = ref([]);
const timeunitOptions = ref([]);

post("dictionary", { root_code: "MATERIAL_TIMEUNIT", name: "天" }).then(data => {
	timeunitOptions.value = data;
});

const materialOptions = ref([]);

post("dictionary", { root_id: 353 }).then(data => {
	//周转箱材料
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);
	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: Infinity, status: 1 }).then(({ data }) => {
		const modelNameOpts = {};
		const selectListOpts = {};
		for (const d of data) {
			if (!modelNameOpts[d.source_id]) modelNameOpts[d.source_id] = [];
			if (!selectListOpts[d.source_id]) selectListOpts[d.source_id] = [];
			const modelName = d.attr ? `${d.model}（${d.attr}）` : d.model;
			if (modelNameOpts[d.source_id].includes(modelName)) continue;
			modelNameOpts[d.source_id].push(modelName);
			selectListOpts[d.source_id].push({
				model: d.model,
				modelName: modelName
			});
		}
		for (const key in selectListOpts) {
			materialModelOptions.value[key] = selectListOpts[key];
		}
		unitOptions.value = [];
		for (const material of formState.value.materials) {
			const units = [];
			for (const d of data) {
				if (d.source_id === material.source_id && d.model === material.model) {
					units.push(d);
				}
			}
			unitOptions.value[`${material.source_id}_${material.model}`] = units;
		}
	});
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;
	record.model = null;
	record.unit = null;
	if (!id) return;
	post("material", { source_id: id, page_size: Infinity, status: 1 }).then(({ data }) => {
		const modelNames = [];
		const selectList = [];
		for (const d of data) {
			const modelName = d.attr ? `${d.model}（${d.attr}）` : d.model;
			if (modelNames.includes(modelName)) continue;
			modelNames.push(modelName);
			selectList.push({
				model: d.model,
				modelName: modelName
			});
		}
		materialModelOptions.value[id] = selectList;
	});
};

const addMaterialModel = () => {
	const item = { key: formState.value.materials.length };
	// 时长不可选, 默认为天
	item.time_unit = timeunitOptions.value[0].name;
	formState.value.materials.push(item);
};

const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
};

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");

const changeMaterialModel = (record, model) => {
	unitOptions.value[record.source_id] = [];
	record.id = null;
	record.unit = null;
	if (!unitOptions.value[`${record.source_id}_${record.model}`]) {
		post("material", { source_id: record.source_id, page_size: Infinity, status: 1 }).then(({ data }) => {
			const selectList = [];
			for (const d of data) {
				if (d.model !== model) {
					continue;
				}
				selectList.push(d);
			}
			unitOptions.value[`${record.source_id}_${record.model}`] = selectList;
		});
	}
};
const submitPurchase = () => {
	proxy.$message.success("总控计划提交成功", 1);
	closeTab("/planzz");
};
const changeMaterialUnit = (record, unit, unitOpt) => {
	const material = unitOpt.filter(item => item.unit === unit)[0];
	record.id = material.id;
};

const uploading = ref(false);
//上传前校验
const beforeUpload = file => {
	uploading.value = true;
	if (file.type !== "application/pdf") {
		proxy.$message.error("只能上传PDF文件");
		uploading.value = false;

		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		uploading.value = false;
		return false;
	}
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.file_path.push({
			name: file.name,
			url: file.response.data.url
		});
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
		uploading.value = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
	}
};
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
